package com.bangcommunity.bbframe.common.base;

import java.io.Serializable;

public class PageInfo implements Serializable {

    private static final long serialVersionUID = 20131015L;

    /**
     * 获取全部内容
     */
    public static final PageInfo ALL = new PageInfo(0, Integer.MAX_VALUE);

    public static final int MAX_PAGE_SIZE = 1000;

    /**
     * offset x means start from number (x + 1)
     */
    private int offset = 0;

    /**
     * page size
     */
    private int size = 10;

    private PageInfo(int offset, int size) {
        this.offset = offset;
        this.size = size;
    }

    /**
     * 从页码、分页大小构建
     *
     * @param page
     *            页码，从1开始
     * @param size
     * @return
     */
    public static PageInfo fromPageAndSize(int page, int size) {
        page = filterPage(page);
        size = filterSize(size);
        return new PageInfo((page - 1) * size, size);
    }

    /**
     * 从偏移量、分页大小构建
     *
     * @param offset
     *            偏移量，从0开始
     * @param size
     * @return
     */
    public static PageInfo fromOffsetAndSize(int offset, int size) {
//        if (offset < 0) {
//            throw new RuntimeException("page info invalid offset cannot less than zero: " + offset);
//        }
//        size = filterSize(size);
        return new PageInfo(offset, size);
    }

    private static int filterPage(int page) {
//        if (page < 1) {
//            throw new RuntimeException("page info invalid pageno cannot less than 1: " + page);
//        }
        return page;
    }

    private static int filterSize(int size) {
//        if (size > MAX_PAGE_SIZE) {
//            throw new RuntimeException("page info invalid max size is " + MAX_PAGE_SIZE + " : " + size);
//        }
//        if (size < 1) {
//            throw new RuntimeException("page info invalid size must greater than zero: " + size);
//        }
        return size;
    }

    public int getOffset() {
        return offset;
    }

    public int getPageNo() {
        return offset / size + 1;
    }

    public int getSize() {
        return size;
    }
}
